import type { IUserInfoVo } from '@/api/types/login'
import { defineStore } from 'pinia'
import { ref } from 'vue'
import {
  // getUserInfo as _getUserInfo,
  login as _login,
  logout as _logout,
  wxLogin as _wxLogin,
  // getWxCode,
} from '@/api/login'
import { getUserData } from '@/api/user'
import { toast } from '@/utils/toast'

// 初始化状态
const userInfoState: IUserInfoVo = {
  id: 0,
  username: '',
  nickname: '',
  avatar: 'https://happybackshop.cn/storage/default/20250918/132837ffaba9af8675a2184e4827e7d9b9d1d3a1fe7.jpeg',
  token: '',
  qrcode: ''
}
// 用户次卡信息
// const userCard = {
// 	"total": 0,
// 	"count": 0,
// 	"settings_card_id": 0,
// 	"settingsCard": {
// 		"id": 0,
// 		"name": "",
// 		"count": 0
// 	}
// }

export const useUserStore = defineStore(
  'user',
  () => {
	const user = uni.getStorageSync('userInfo')
    // 定义用户信息
    const userInfo = ref<IUserInfoVo>(user ? user : { ...userInfoState })
	// 等级数组
	const levelArr = ref([])
	// 用户次卡信息
	// const userCardInfo = ref(userCard)
	const userCardInfo = ref([])
	// 积分更新时间
	const scoreUpdateTime = ref('')
    // 设置用户信息
    const setUserInfo = (val: IUserInfoVo) => {
      console.log('设置用户信息', val)
	  if (!val) return
      // 若头像为空 则使用默认头像
      if (!val.avatar || val.avatar === '/static/images/avatar.png') {
        val.avatar = userInfoState.avatar
      }
	  uni.setStorageSync('userInfo', val)
	  uni.setStorageSync('token', val.token)

      userInfo.value = val
    }
    const setUserAvatar = (avatar: string) => {
      userInfo.value.avatar = avatar
      console.log('设置用户头像', avatar)
      console.log('userInfo', userInfo.value)
    }
    // 删除用户信息
    const removeUserInfo = () => {
      userInfo.value = { ...userInfoState }
	  // userCardInfo.value = { ...userCard }
	  userCardInfo.value = []
      uni.removeStorageSync('userInfo')
      uni.removeStorageSync('token')
    }
	// 设置二维码值
	const setUserQrcode = (value: any) => {
		userInfo.value.qrcode = value
	}
	// 设置等级数组数据
	const setLevelArr = (data: any) => {
		levelArr.value = data
	}
	// 设置用户次卡信息
	const setUserCard = (data: any) => {
		userCardInfo.value = data
	}
    /**
     * 获取用户信息
     */
    const getUserInfo = async () => {
      const res = await getUserData()
	 //  const userInfo = {
		// id: 1,
		// "username": "user",
		// "nickname": "User",
		// "email": "18888888888@qq.com",
		// "mobile": "18888888888",
		// "avatar": import.meta.env.VITE_IMG_URL_PREFIX + "/storage/default/20250729/下载fe591b75e0e8a9fbec3dba77963dba84b8c0c918.jpeg",
		// "gender": 2,
		// "birthday": "2025-07-21",
		// "money": "0.00",
		// "score": 111,
		// "score_total": 10,
		// "last_login_time": 1756280791,
		// "last_login_ip": "121.40.174.66",
		// "join_time": null,
		// "motto": "",
		// "token": "1a80e03c-e7c8-42f4-a3ae-6c6eff671115",
		// "refresh_token": ""
	 //  }
	 const { userInfo } = res
	  setUserInfo(userInfo)
      // TODO 这里可以增加获取用户路由的方法 根据用户的角色动态生成路由
      return userInfo
    }
    /**
     * 用户登录
     * @param credentials 登录参数
     * @returns R<IUserLogin>
     */
    const login = async (credentials: {
      username: string
      password: string
      code: string
      uuid: string
    }) => {
      const res = await _login(credentials)
      console.log('登录信息', res)
      toast.success('登录成功')
      await getUserInfo()
      return res
    }

    /**
     * 退出登录 并 删除用户信息
     */
    const logout = async () => {
      _logout()
      removeUserInfo()
    }
    /**
     * 微信登录
     */
    const wxLogin = async (params: AnyObject) => {
      // 获取微信小程序登录的code
      // const codeRes = await getWxCode()
	  
      // console.log('微信登录code', codeRes)
	  
		const res = await _wxLogin(params)
		setUserInfo({
			...res.userInfo
		})
		// await getUserInfo()
		// return res
		// return res
    }
	// 登录操作
	const handleLogin = async (res: AnyObject) => {
		if (!res.code) return
		// console.log('handleLogin', res)
		uni.login({
		    provider: 'weixin',
		    success: function (loginRes) {
		        const { errMsg = '', ...other } = { ...res }
				// console.log('uni.login', loginRes)
				wxLogin({
					we_code: loginRes.code,
					...other,
				})
		    }
		});
	}
	
	// 获取用户当前等级
	const getUserLevel = computed(() => {
		const { score_total = 0 } = userInfo.value
		
		const { name = '' } = { ...levelArr.value.find((item: AnyObject) => (score_total >= item.start && score_total <= item.end)) }
		
		return name
	})

    return {
      userInfo,
      login,
      wxLogin,
      getUserInfo,
      setUserAvatar,
      logout,
	  handleLogin,
	  setUserQrcode, 
	  levelArr,
	  setLevelArr,
	  setUserInfo,
	  userCardInfo,
	  setUserCard,
	  getUserLevel,
	  scoreUpdateTime
    }
  },
  {
    persist: false,
  },
)
